<template>
  <FModal ref="FModal" header="编辑公式" width="890" @ok="ok">
    <div class="flow-title-formula-wrapper" v-loading="loading">
      <div @keydown="stopEvent" style="min-height: 145px; height: fit-content; z-index: 10; max-height: 400px">
        <el-input ref="area" type="textarea" @mouseup="selectionChange"
                  @keyup="selectionChange" v-focus v-model="formula.formulaText"
                  :rows="6" style="min-height: 145px; max-height: 390px"/>
      </div>

      <div class="flow-variables-wrapper">
        <div class="flow-variables-left">
          <el-tabs style="height: calc(100% - 30px)"
                   v-model="showPanel" @tab-change="showPanelChange">
            <el-tab-pane style="height: 100%" name="formFields" label="表单数据域">
              <div class="flow-variables-list-wrapper">
                <FList size="small" bordered key-name="formFieldVariable" @select="selectVariableChange"
                       @doubleClick="addFormField" :selected-key="selectedVariableKey"
                       title-name="formFieldVariableShowName" :data-source="formFields"/>
              </div>
            </el-tab-pane>
            <el-tab-pane style="height: 100%" name="unit" label="组织机构变量">
              <div class="flow-variables-list-wrapper">
                <FList size="small" bordered key-name="value" @select="selectSystemVariableChange"
                       @doubleClick="(v) => insertIntoFormula(v.value)"
                       :selected-key="selectedVariableKey"
                       title-name="title" :data-source="UnitVariables"/>
              </div>
            </el-tab-pane>
            <el-tab-pane style="height: 100%" name="date" label="日期变量">
              <div class="flow-variables-list-wrapper">
                <FList size="small" bordered key-name="value" @select="selectSystemVariableChange"
                       @doubleClick="(v) => insertIntoFormula(v.value)"
                       :selected-key="selectedVariableKey"
                       title-name="title" :data-source="DateVariables"/>
              </div>
            </el-tab-pane>
            <el-tab-pane style="height: 100%" name="system" label="系统数据域">
              <div class="flow-variables-list-wrapper">
                <FList size="small" bordered key-name="value" @select="selectSystemVariableChange"
                       @doubleClick="(v) => insertIntoFormula(v.value)"
                       :selected-key="selectedVariableKey"
                       title-name="title" :data-source="SystemField"/>
              </div>
            </el-tab-pane>
            <el-tab-pane style="height: 100%" name="constants" label="自定义常量">
              <div class="flow-variables-list-wrapper">
                <FList size="small" bordered key-name="value" @select="selectSystemVariableChange"
                       @doubleClick="(v) => insertIntoFormula(v.value)"
                       :selected-key="selectedVariableKey"
                       title-name="title" :data-source="SystemConstField"/>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <el-scrollbar class="flow-variables-right">
          <el-button @click="() => insertIntoFormula('+')">+</el-button>
          <el-button @click="() => insertIntoFormula('-')">-</el-button>
          <el-button @click="() => insertIntoFormula('*')">*</el-button>
          <el-button @click="() => insertIntoFormula('/')">/</el-button>

          <el-button @click="() => insertIntoFormula('(')">(</el-button>
          <el-button @click="() => insertIntoFormula(')')">)</el-button>

          <el-divider/>
          <el-button @click="() => insertIntoFormula('+')">+</el-button>
          <el-button @click="() => insertIntoFormula('==')">==</el-button>
          <el-button @click="() => insertIntoFormula('!=')">!=</el-button>
          <el-button @click="() => insertIntoFormula('>=')">&gt;=</el-button>
          <el-button @click="() => insertIntoFormula('<=')">&lt;=</el-button>
          <el-button @click="() => insertIntoFormula('<')"> &lt;</el-button>
          <el-button @click="() => insertIntoFormula('>')"> &gt;</el-button>

          <el-divider/>
          <el-button @click="() => insertIntoFormula('&&')">and</el-button>
          <el-button @click="() => insertIntoFormula('||')">or</el-button>
          <el-button @click="() => insertIntoFormula('in()', -1)">in</el-button>
          <el-button @click="() => insertIntoFormula('!')">not</el-button>

          <el-divider/>
          <el-button>日期差</el-button>
          <el-button>日期时间差</el-button>
          <el-button>明细合计</el-button>
          <el-button>明细平均</el-button>
          <el-button>明细最大</el-button>
          <el-button>明细最小</el-button>

          <el-divider/>
          <el-button @click="() => insertIntoFormula('any()', -1)">明细任意一行</el-button>
          <el-button @click="() => insertIntoFormula('every()', -1)">明细所有行</el-button>
          <el-button @click="() => insertIntoFormula('listItemEq(,)', -2)">明细等于</el-button>
          <el-button>取年</el-button>
          <el-button>取月</el-button>
          <el-button>取日</el-button>
          <el-button @click="createExtendValue">extend</el-button>

          <el-divider/>
          <el-button>取星期几</el-button>
          <el-button>取日期</el-button>
          <el-button>取时间</el-button>
          <el-button @click="() => insertIntoFormula('isEmpty()', -1)">是否为空</el-button>
        </el-scrollbar>
      </div>
    </div>
  </FModal>
  <FormFieldValueCreateModal @addVariable="addVariable" ref="FormFieldValueCreateModal"/>
</template>
<script>
import FModal from '@/components/FModal/index.vue';
import FList from '@/components/FList/index.vue';
import {DefaultFormDefinition} from '@/components/form/DefaultFormDefinition';
import {isEmpty} from '@/utils/CommonUtils';
import FormDefinitionHelper from '@/components/form/FromDesigner/FormDefinitionHelper';
import {postAction} from '@/request/BaseRequest';
import {DateVariables, SystemConstField, SystemField, UnitVariables} from '@/components/form/SystemVariables';
import {resolveFieldTypeByComponentName} from '@/components/form/DesignComponents';
import FormFieldValueCreateModal from '@/components/formula/FormFieldValueCreateModal/index.vue';

export default {
  name: "FormulaEditor",
  components: {
    FormFieldValueCreateModal,
    FModal,
    FList,
  },
  data() {
    return {
      UnitVariables,
      DateVariables,
      SystemConstField,
      SystemField,
      loading: false,
      resultType: undefined,
      selectedVariableKey: undefined,
      showPanel: 'formFields',
      originFormula: undefined,
      formula: {
        id: undefined,
        formulaText: undefined,
        formulaTitle: undefined,
        formulaRefs: null,
      },
      formDefinition: DefaultFormDefinition,
      formFields: [],
      selectionStart: -1,
      selectionEnd: -1
    };
  },
  methods: {
    setData(formDefinition, formula, resultType) {
      this.resultType = resultType;
      this.formDefinition = formDefinition;
      this.originFormula = formula;
      this.formula = JSON.parse(JSON.stringify(formula));
      this.resolveFields();
      this.open();
      this.showPanel = 'formFields';
    },
    resolveFields() {
      let helper = new FormDefinitionHelper(this.formDefinition);
      let fieldVos = helper.getFieldVos();
      this.formFields = fieldVos;
    },
    addFormField(formField) {
      let variable = formField.formFieldVariable;
      let fieldType = resolveFieldTypeByComponentName(formField.fieldComponent);
      let fieldShowName = formField.fieldShowName;

      let fieldText = '{' + `${variable}:${fieldType}:${fieldShowName}` + '}';
      this.insertIntoFormula(fieldText);
    },
    selectSystemVariableChange(variable) {
      this.selectedVariableKey = variable.value;
    },
    selectVariableChange(variable) {
      this.selectingFormVariable = variable;
      this.selectedVariableKey = variable.formFieldVariable;
    },
    ok() {
      if (isEmpty(this.formula.formulaText)) {
        this.$message.warning('请配置公式');
        return;
      }
      this.loading = true;
      postAction('/script/translate', {
        formula: this.formula.formulaText,
        resultType: this.resultType
      }).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          this.setTranslatedFormulaData(result);
          this.close();
          this.$emit('formulaEditOK')
        }
      });
    },
    setTranslatedFormulaData(result) {
      this.formula.formulaTitle = result.formulaTranslated;
      this.formula.formulaRefs = result.formulaRefs;

      this.originFormula.formulaTitle = this.formula.formulaTitle;
      this.originFormula.formulaText = this.formula.formulaText;
      this.originFormula.formulaRefs = this.formula.formulaRefs;
    },
    close() {
      this.$refs.FModal.close();
      this.clearDatas();
    },
    clearDatas() {
      this.selectedVariableKey = undefined;
      this.showPanel = 'formFields';
      this.originFormula = undefined;
      this.formula = {
        id: undefined,
        formulaText: undefined,
        formulaTitle: undefined,
        formulaRefs: null,
      };
      this.formFields = [];
      this.selectionStart = -1;
      this.selectionEnd = -1;
    },
    insertIntoFormula(text, offset = 0) {
      let tempFormulaText = this.formula.formulaText;
      if (isEmpty(tempFormulaText)) tempFormulaText = '';
      if (this.selectionStart < 0) {
        tempFormulaText += text;
        this.selectionStart = text.length + offset
        this.selectionEnd = this.selectionStart;
      } else {
        tempFormulaText = this.doInsertInfoFormula(tempFormulaText, text, offset);
      }
      this.formula.formulaText = tempFormulaText;
    },
    doInsertInfoFormula(tempFormulaText, text, offset) {
      let start = tempFormulaText.substring(0, this.selectionStart);
      let end = tempFormulaText.substring(this.selectionEnd);
      if (isEmpty(start)) start = '';
      if (isEmpty(end)) end = '';
      tempFormulaText = start + text + end;
      this.selectionStart += (text.length + offset);
      this.selectionEnd = this.selectionStart;

      return tempFormulaText;
    },
    selectedKeyChange(selectField) {
      this.selectedKey = selectField.id;
    },
    createExtendValue() {
      if (isEmpty(this.selectedVariableKey)) return;
      this.$refs.FormFieldValueCreateModal.setData(this.selectingFormVariable);
    },
    addVariable(variable) {
      this.insertIntoFormula(variable)
    },
    open() {
      this.selectedKey = undefined;
      this.selectionStart = -1;
      this.selectionEnd = -1;
      this.$refs.FModal.open();
    },
    showPanelChange(showPanel) {
      this.showPanel = showPanel;
    },
    stopEvent(e) {
      e.stopPropagation();
    },
    selectionChange() {
      let element = document.activeElement;
      this.selectionStart = element.selectionStart;
      this.selectionEnd = element.selectionEnd;
    },
  }
};

</script>

<style scoped>
.flow-title-formula-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.flow-variables-wrapper {
  width: 100%;
  margin: 10px 0;
  padding: 0 5px;
  display: flex;
  min-height: 0;
  flex: 1;
}

.flow-variables-left {
  flex: 1;
  padding-right: 20px;
}

.flow-variables-list-wrapper {
  height: 100%;
}

.flow-variables-right {
  width: 375px;
  min-height: 500px;
}
</style>

<style>
.flow-variables-right button {
  margin: 0 10px 10px 0;
}

.flow-variables-right .el-button + .el-button {
  margin-left: 0;
}

.flow-title-formula-wrapper .el-tabs__content {
  height: calc(100% - 22px);
}

.flow-title-formula-wrapper .el-divider--horizontal {
  margin: 0 0 10px 0;
}
</style>
